import flask
import lstm_model
from flask import request
import numpy as np
from keras.models import load_model

# 实例化 flask
app = flask.Flask(__name__)

# 加载模型
model1 = load_model('lstm.h5')


# 将预测函数定义为一个路由
@app.route("/predict", methods=["GET", "POST"])
def predict():
    res = {"success": False}
    input_str = request.args.get('str')
    if not input_str or len(input_str) == 0:
        return "输入异常"
    # elif len(input_str) > lstm_model.seq_len:
    #     input_str = input_str[0:lstm_model.seq_len]
    # elif len(input_str) < lstm_model.seq_len:
    #     input_str = input_str + ' ' * (lstm_model.seq_len - len(input_str))
    input_str_trans = lstm_model.transform_data(input_str)
    y_predict = model1.predict(input_str_trans)  # Make predictions using the model
    y_predict = [i for i in np.argmax(y_predict[0], axis=1)]
    y_predict = lstm_model.int_res_to_char(y_predict)
    res["success"] = y_predict
    # 返回Json格式的响应
    return flask.jsonify(res)


# 启动Flask应用程序，允许远程连接
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=8888)
